package ee.serge.util;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

import ee.serge.client.AlertBox;
import ee.serge.client.Move;
import ee.serge.client.content.PageNotFoundContent;
import ee.serge.client.content.cp.LoginContent;
import ee.serge.shared.BusinessException;
import ee.serge.shared.HandledException;
import ee.serge.shared.LoginException;
import ee.serge.shared.NotFoundException;

public abstract class SimpleCallback<T> implements AsyncCallback<T> { 
   
   public SimpleCallback() {
      Loader.show();
   }
   
   @Override
   public final void onFailure(Throwable caught) {
   	System.out.println(caught);
   	GWT.log(caught.getMessage());
   	Loader.show();
   	failure();
      Loader.hide();
      if (caught instanceof HandledException) {
         if (caught instanceof LoginException) {
            Move.get().goToURLData(LoginContent.getURLData());
            AlertBox.showError("You must be logged in to view this content");
         } else if (caught instanceof BusinessException) {
            AlertBox.showError(caught.getMessage());
         } else if (caught instanceof NotFoundException) {
            Move.get().goToURLData(PageNotFoundContent.getURLData());
         } else {
            AlertBox.showError(caught.getMessage());
            throw new RuntimeException(caught);
         }
      } else {
         AlertBox.showError(caught.getMessage());
         throw new RuntimeException(caught);
      }
      
   }
   
   public abstract void success(T result);
   
   public void failure() {
   	
   }
   
   @Override
   public final void onSuccess(T result) {
      Loader.hide();
      success(result);
   }
   
}
